package team.lourd.network.system.batch.ext.support;

import net.sf.json.JSONObject;
import org.springframework.util.StringUtils;
import team.lourd.network.system.batch.domian.ProcessMeta;
import team.lourd.network.system.batch.ext.ProcessExecutor;
import team.lourd.network.system.batch.ext.ReturnValue;
import team.lourd.network.system.own.domain.pretrem.PMType;
import team.lourd.network.system.utils.web.HttpUtil;

import java.io.IOException;

/**
 * 基础的元素处理器(处理API的调用)
 *
 * @author JADemo
 * @date 2019/2/19 10:00
 */
public class BaseProcessExecutor implements ProcessExecutor {
    // 返回支持的模型
    @Override
    public boolean support(ProcessMeta processMeta) {
        return processMeta.getType() == PMType.API;
    }

    // 执行元素表达式
    @Override
    public ReturnValue execute(ProcessMeta processMeta) {
        ReturnValue returnValue = new ReturnValue();
        // 获取表达式体(API地址)
        String processExpressionBody = processMeta.getProcessExpression();
        // 如果从表达式中无法获取到API地址就从目标地址获取
        if (StringUtils.isEmpty(processExpressionBody)) {
            processExpressionBody = processMeta.getTarget();
        }
        // API返回值
        JSONObject body;
        try {
            // 调用目标API
            body = HttpUtil.doGetJson(processExpressionBody);
        } catch (IOException e) {
            body = null;
        }
        // 设置返回值的内容
        returnValue.setResult(body);
        if (body != null) {
            // 设置返回值的类型
            returnValue.setType(JSONObject.class);
            // 设置返回值的状态(正常返回)
            returnValue.setState(0);
        } else {
            // 失败的返回值
            returnValue.setState(-1);
        }
        return returnValue;
    }
}
